package com.yanqu.road.server.manager.banquet;

import com.yanqu.road.entity.banquet.cross.CrossBanquetData;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossPartyChatMgr extends TempMgr {

    public static final int MAX_MESSAGE_COUNT = 50;

    private static Map<String, WorldMessageProto.WorldMessageListMsg.Builder> chatMsgMap;

    @Override
    public boolean reloadData() {
        chatMsgMap = new ConcurrentHashMap<>();
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void banquetChat(String banquetId, WorldMessageProto.WorldMessageTempMsg chatMsg){
        CrossBanquetData banquetData = CrossPartyMgr.getParty(banquetId);
        if(!chatMsgMap.containsKey(banquetId)){
            synchronized (chatMsgMap){
                if(!chatMsgMap.containsKey(banquetId)){
                    chatMsgMap.put(banquetId, WorldMessageProto.WorldMessageListMsg.newBuilder());
                }
            }
        }

        WorldMessageProto.WorldMessageListMsg.Builder chatListMsg = chatMsgMap.get(banquetId);
        synchronized (chatListMsg){
            if(chatListMsg.getDataListCount() >= MAX_MESSAGE_COUNT){
                chatListMsg.removeDataList(0);
            }
            chatListMsg.addDataList(chatMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.A_WORLD_MESSAGE_TRANSFER, chatMsg);


        if("0".equals(banquetData.getServerListStr())){
            int channelId = ConfigHelper.getInt("channelId");
            for(ServerInfo serverInfo : ServerListMgr.getOpenServerList(channelId)){
                MessageHelper.sendPacket(serverInfo.getServerId(), 0,pbMsg );
            }
        }else{
            List<Integer> serverIdList = banquetData.getServerList();
            for(Integer serverId : serverIdList){
                MessageHelper.sendPacket(serverId, 0, pbMsg);
            }
        }
    }

    public static WorldMessageProto.WorldMessageListMsg.Builder getChatListMsg(String banquetId){
        return chatMsgMap.get(banquetId);
    }
}
